import { useNavigate } from 'react-router-dom'
import { useEffect, useState, useRef } from 'react'
import "./index.css"
import { useSetState } from "ahooks"
import { Input } from 'antd'
const { TextArea } = Input;
import store from "@/store"
import { loginClient } from "@/apis"
import { mockVioceList } from "./config"
import AudioPlayer from "../../components/AudioPlayer"

const VITE_VISIT_URL = import.meta.env.VITE_VISIT_URL
import { appendQueryParameters, parseQueryParameters, getAuth } from "@/utils"
export default function LiveRoom() {


    const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
    const randomAvatar = () => Array.from({ length: 2 }, (v, i) => `./avatar/${random(1, 8)}.webp`)
    const navigate = useNavigate()
    const initialized = useRef(false);
    const [data, setData] = useSetState({
        peopleNumber: random(50, 100),
        avatar: randomAvatar()
    })
    // const textAreaRef = useRef(null);
    const [inputFlag, setInputFlag] = useState(false)
    //进入直播间状态
    const [isEnter, setIsEnter] = useState(false)
    const commentAreaRef = useRef(null);
    const inputRef = useRef(null);
    const audioRef = useRef(null);
    const videoRef = useRef(null);
    const inputRefBox = useRef(null);
    const [inputValue, setInputValue] = useState("")
    const [nickName, setNickName] = useState("")
    const [avatarUrl, setAvatarUrl] = useState("./avatar/1.webp")
    // const []
    const [answerUrl, setAnswerUrl] = useState("")
    const [answerList, setAnswerList] = useState("")
    //
    const [isMuted, setIsMuted] = useState(false)
    const [ poster,setPoster] = useState("") // 视频预览图

    const audioElement = useRef(null);
    const [commentValue, setCommentValue] = useState([
        // { name: "会飞的鱼🐟：", meassage: "巴啦啦能量" },
    ])

    const [loop, setLoop] = useState(true) // 音频循环
    const [currentIndex, setCurrentIndex] = useState(0); // 音频当前播放的索引
    const addComent = (item) => {
        setCommentValue(preValue => {
            return [...preValue, item]
        });
        // commentAreaRef.current.scrollTop = commentAreaRef.current.scrollHeight;
        smoothScrollToBottom(commentAreaRef.current) // 动画效果
    }
    const initComment = [
        // { name: "会飞的鱼🐟", meassage: "" },
        { name: "- 欢迎来到直播间！抖音严禁未成年人直播或打赏。直播间内严禁出现违法违规、低俗色情、吸烟酗酒、人身伤害等内容。如主播在直播过程中以不当方式诱导打赏、私下交易，请谨慎判断，以防人身财产损失。请大家注意财产安全，谨防网络诈骗。实际下载应用，请以明示信息为准。经主播授权当前直播间在抖音盒子分发，您在直播间内的公开信息（如互动信息、内容）将同时在抖音盒子展示。", meassage: "" }
    ]
    const initWeixinLogin = async () => {
        if (!token && !userInfo) {
            console.log("没有token")

            let match = window.location.href.match(/[?&]code=([^&]+)/);
            match && store.set("authCode", match[1])
            // console.log("user.getAuthCode", user.getAuthCode)
            let redirectUrl = appendQueryParameters(
                `${VITE_VISIT_URL}/#/`,
            );
            !store.get("authCode") && getAuth({
                url: redirectUrl
            });
            if (!store.get("authCode")) return;
            const paramsData = parseQueryParameters(window.location.href);
            let res = paramsData.code ? await loginClient({
                authCode: paramsData.code,
                // salesmanId: paramsData.salesmanId,
            }) : null
            // res && user.setToken(res.token);
            // res && user.setUserInfo(res);
            res && store.set("token", res.token);
            res && store.set("userInfo", res, true);
            res && setNickName(res['nickname'])
            const resCommiss = await commissionAccount()
            commission.value = resCommiss
        } else {
            console.log("登录过")
            setNickName(userInfo['nickname'])

        }
    }
    const initUser = async () => {
        const token = store.get("token")
        const userInfo = store.get("userInfo", true)

        // initWeixinLogin()
    }

    useEffect(() => {
        initUser()
    }, [])

    const handleAudioEnd = () => {
        handlePlayEnd(currentIndex)
        if (loop) {
            //判断是否有音频需要插入播放 
            if (answerList.length != 0) {
                setAnswerUrl(answerList[0])
                //删除第一个 setAnswerList
                setAnswerList(preValue => preValue.slice(1))
            } else {
                let nextIndex = currentIndex + 1;
                if (nextIndex >= mockVioceList.length) {
                    nextIndex = 0;
                }
                setCurrentIndex(nextIndex);
            }
            //
            if (audioRef.current) {
                // 监听audioRef.current 是否load完成 
                audioRef.current.addEventListener('canplaythrough', () => {
                    audioRef.current.play().catch(error => {
                        console.error('Error playing audio:', error);
                    });
                });
            }
        } else {
            setIsPlaying(false);
        }

    };
    //音频监听播放
    useEffect(() => {
        if (audioRef.current) {
            // 监听音频结束事件
            audioRef.current.addEventListener('ended', handleAudioEnd);
            return () => {
                // 清理事件监听器
                audioRef.current.removeEventListener('ended', handleAudioEnd);
            };
        }
    }, [audioRef, handleAudioEnd]); // 注意这里的依赖数组
    useEffect(() => {
        // 当currentIndex变化时，加载并播放新的音频文件
        if (audioRef.current && currentIndex >= 0 && currentIndex < mockVioceList.length) {
            audioRef.current.src = mockVioceList[currentIndex];
            audioRef.current.load();
            audioRef.current.addEventListener('canplaythrough', () => {
                audioRef.current.play().catch(error => {
                    console.error('Error playing audio:', error);
                });
            });
        }
    }, [currentIndex, audioRef, mockVioceList]); // 这里依赖于currentIndex和audioRef


    const handlePlayEnd = (currentIndex) => {
        console.log(`音频 ${currentIndex} 播放结束`);
        setAnswerUrl("")
        // 在这里你可以执行一些逻辑，比如决定是否停止播放或进行其他操作
        // 判断是否有音频需要插入  插入音频 currentIndex 保持预加载
    };

    const handleComment = () => {
        initComment.forEach(((item, index) => {
            setTimeout(() => {
                addComent(item)
            }, index * random(2000, 4000));
        }))
    }

    // 初始添加评论数据
    useEffect(() => {
        if (!initialized.current) {
            initialized.current = true;
        }
        // setInterval(() => {
        //     addComent({ name: "会飞的鱼🐟：", meassage: "巴啦啦能量" + random(1, 100000) })
        // }, 4000);


        // setTimeout(() => {
        //     setAnswerList([...answerList,"https://sgpub.oss-cn-shenzhen.aliyuncs.com/trv/20240717/a775fce64cf84897a90329c47936c06e.wav"])
        //     console.log("有一条回答等待话说完播放")
        // }, random(3000, 10000));
    }, [])

    //视频画面第一帧的处理
    useEffect(() => {
        if (videoRef.current) {
            const videoElement = document.createElement('video');
            videoElement.src = './video.mp4'; // 你的视频源
            videoElement.autoplay = false; // 不自动播放，因为我们只想获取第一帧
            videoElement.muted = true; // 保持静音，避免自动播放声音

            // 创建一个canvas元素来捕获帧
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            videoElement.addEventListener('loadedmetadata', () => {
                // 设置canvas尺寸与视频相同
                canvas.width = videoElement.videoWidth;
                canvas.height = videoElement.videoHeight;

                // 绘制第一帧到canvas
                videoElement.currentTime = 0; // 确保回到视频开始
                videoElement.pause(); // 暂停视频
                ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

                // 将canvas内容转换为DataURL
                const dataURL = canvas.toDataURL('image/jpeg'); // 可以选择不同的格式，如'image/png'

                // 设置video的poster属性
                // videoElement.poster = dataURL;
                setPoster(dataURL);
            });
        }
    }, [])

    const smoothScrollToBottom = (element) => {
        const start = element.scrollTop;
        const change = element.scrollHeight - start;
        const duration = 300; // 滚动动画的持续时间

        let startTime = null;

        const animateScroll = (timestamp) => {
            if (!startTime) startTime = timestamp;
            const progress = timestamp - startTime;
            const percentage = Math.min(progress / duration, 1);
            element.scrollTop = start + change * percentage;

            if (progress < duration) {
                requestAnimationFrame(animateScroll);
            }
        };

        requestAnimationFrame(animateScroll);
    };
    // input 空间的监听
    useEffect(() => {
        const handleFocus = () => {
            console.log('Input focused, keyboard shown');
            // 调整inputRefBox子元素div宽度为100%
            inputRefBox.current.style.width = '80%';
            //   inputRefBox.current.style.margin = '100%';
            setInputFlag(true)

            //    bg-white p-10 h-50
            document.querySelectorAll(".inputBox")[0].style.bottom = "0"
            document.querySelectorAll(".inputBox")[0].style.backgroundColor = "white";
            document.querySelectorAll(".inputBox")[0].style.padding = '10px';
            document.querySelectorAll(".inputBox")[0].style.height = '50px';



        };

        const handleBlur = () => {
            console.log('Input blurred, keyboard hidden');
            // 在这里恢复弹窗的原始位置，例如：
            // commentAreaRef.current.style.bottom = '45px';
            // inputRefBox.current.style.width = 'w-[calc(100%-196px)]';
            inputRefBox.current.style.width = 'calc(100% - 196px)';
            document.querySelectorAll(".inputBox")[0].style.bottom = "10px"
            document.querySelectorAll(".inputBox")[0].style.backgroundColor = "";
            document.querySelectorAll(".inputBox")[0].style.padding = '0px';
            document.querySelectorAll(".inputBox")[0].style.height = '30px';
            setTimeout(() => {
                setInputFlag(false)
            }, 0);
        };

        inputRef.current.addEventListener('focus', handleFocus);
        inputRef.current.addEventListener('blur', handleBlur);

        return () => {
            if (inputRef.current) {
                inputRef.current.removeEventListener('focus', handleFocus);
                inputRef.current.removeEventListener('blur', handleBlur);
            }
        };
    }, []);

    const handlePlay = () => {
        document.querySelectorAll("video")[0].play();
        setIsMuted(true)
        audioRef.current.play();
        // playButton 按钮 消失
        document.querySelectorAll(".playButton")[0].style.display = "none"
        setIsEnter(true)
        handleComment()
        // console.log("audioElement.value",audioElement)
    }
    const handleSend = () => {
        // console.log("handleSend function called");
        // console.log("inputValue",inputValue);
        addComent({ name: nickName || "害群鼠🐀", meassage: inputValue, identity: 'mine', level: "1" })
        setInputValue("")
        setInputFlag(false)

        setAnswerList([...answerList, "https://sgpub.oss-cn-shenzhen.aliyuncs.com/trv/20240717/a775fce64cf84897a90329c47936c06e.wav"])

    }


    return (

        <div className="w-[100vw] h-[100vh]  video-container">
            <video className='w-[100%] h-[100%]' loop muted src='./video.mp4' ref={videoRef}></video>
            {/* 左上 */}
            <div className='absolute top-0 left-0  h-[36px] bg-[rgba(61,56,50,0.4)] rounded-18 fl mt-4 ml-12 p-2 text-white'>
                <div className='w-32 h-32 bg-[#D8D8D8] rounded-full'></div>
                <div className='w-72 flex flex-col'>
                    <div className='text-[12px]'>芮芮南油工...</div>
                    <div className='text-[10px]'>1.6万本场点赞</div>
                </div>
                <div className='w-40 h-28 rounded-14 fc text-white' style={{ background: 'linear-gradient( 270deg, #FF2B62 0%, #FF2787 100%)' }}>关注</div>
            </div>
            {/* 右上 人数显示*/}
            <div className='absolute top-0 right-0 h-[20px]  flex p-8 items-center mt-13'>
                {data.avatar.map((item, index) => <img key={index} src={item} className='w-[26px] h-[26px] rounded-full mr-4' />)}
                <img src={avatarUrl} className='w-[26px] h-[26px] rounded-full mr-4' />
                <div className='w-[26px] h-[26px] rounded-full mr-4 bg-[#7F7A81] fc text-white'> <div className='scale-50'>{data.peopleNumber}</div> </div>
                <div className='w-[20px] h-[20px] rounded-full mr-4  fc text-white'> <img className='w-12 h-12' src='./icon/delete.png'></img> </div>
            </div>

            {/* 评论区 */}

            {isEnter && <div className='absolute bottom-[45px] left-4 w-[80%] h-[220px] '>
                <div className='w-[100%] h-[100%] overflow-y-auto comment-area' ref={commentAreaRef}>
                    {commentValue.map((item, index) => <div key={index} className='flex flex-wrap text-14 font-[500]'>
                        <div className='bg-[rgba(61,56,50,0.4)] rounded-20 mr-4 text-[#8DCED9] p-4 px-8 m-4 fl flex-wrap'>
                            {item['level'] && <div className='bg-[#6C7397] w-34 h-14 flex items-center rounded-10 text-12 scale-80 justify-center text-white mr-5'> <img className='w-10 h-10 mr-3' src='./icon/level.png'></img>{item.level}</div>}
                            <span className='text-[16px]'>{item.name}</span>
                            {item['identity'] === 'mine' && <div className='border-1 border-solid border-[#8DCED9] rounded-50 w-[26px] scale-[0.65] fc h-[20px]'>我</div>}
                            {item.meassage && '：'}
                            <span className='text-white'>{item.meassage}</span>
                        </div>
                    </div>)}
                </div>
            </div>}
            {/* 左下 右下 回复*/}
            <div className='absolute bottom-[10px] left-0 w-[100%] h-[30px] fc justify-between inputBox '  >
                <div className='w-[calc(100%-196px)]  relative' ref={inputRefBox}>
                    <input style={{ border: 'none', paddingLeft: '10px' }} ref={inputRef} value={inputValue} onChange={(e) => setInputValue(e.target.value)} placeholder="说点什么..." className='w-[100%] h-36 rounded-20 bg-[rgba(61,56,50,0.4)] border-0 ml-8'></input>
                </div>
                {!inputFlag && <div className='fl '>
                    <div className='w-[36px] h-[36px] rounded-full mr-8 fc text-white bg-[rgba(61,56,50,0.4)]'> <img className='w-36 h-36' src='./icon/url@2x.png'></img> </div>
                    <div className='w-[36px] h-[36px] rounded-full mr-8 fc text-white bg-[rgba(61,56,50,0.4)]'> <img className='w-36 h-36' src='./icon/car@2x.png'></img> </div>
                    <div className='w-[36px] h-[36px] rounded-full mr-8 fc text-white bg-[rgba(61,56,50,0.4)]'> <img className='w-36 h-36' src='./icon/gift@2x.png'></img> </div>
                    <div className='w-[36px] h-[36px] rounded-full mr-8 fc text-white bg-[rgba(61,56,50,0.4)]'> <img className='w-36 h-36' src='./icon/more@2x.png'></img> </div>
                </div>}
                {inputFlag && <div className='fc bg-[#FC2952] text-white p-4 px-8 rounded-15 text-14' onClick={handleSend}>发送</div>}
            </div>

            {/* 中间 play*/}
            <div className='playButton absolute top-[50%] left-[50%] translate-x-[-50%] translate-y-[-50%] w-[120px] h-[120px] fc' onClick={handlePlay}>
                <img src='../icon/download.png' className='w-[110px] h-[110px]' />
            </div>

            <div className='absolute top-10 z-50'>
                <audio poster={poster} src={answerUrl || mockVioceList[currentIndex]} ref={audioRef} ></audio>
            </div>



            {/* <AudioPlayer playFromIndex={handlePlayFromIndex}  audioSources={mockVioceList} startIndex={currentIndex} loop={true} onPlayEnd={handlePlayEnd}  audioElement={audioElement} /> */}
        </div>
    )
}